<template>
  <div style="padding: 5px">
    <el-row :gutter="8" v-for="item in items" :key="item.id" style="margin-bottom: 5px">
      <el-col :span="8">
        <el-input v-model="item.name" maxlength="50" placeholder="参数名" />
      </el-col>
      <el-col :span="1" style="text-align: center">=</el-col>
      <el-col :span="13">
        <el-input v-model="item.value" maxlength="50" placeholder="参数值" />
      </el-col>
      <el-col :span="2">
        <BaseButton type="danger" circle :icon="dropIcon" @click="drop(item)" />
      </el-col>
    </el-row>
    <div>
      <el-button type="success" @click="add">新增</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes'
import { ref, unref, watch, onMounted } from 'vue'
import { ObjKeyValItem } from '../types'
import { useIcon } from '@/hooks/web/useIcon'

const emit = defineEmits(['update:modelValue'])
const dropIcon = useIcon({ icon: 'ep:delete' })
const props = defineProps({
  modelValue: propTypes.object
})
const items = ref<ObjKeyValItem[]>([])
onMounted(() => {
  reset(props.modelValue)
})
let id = 0
const reset = (val: object) => {
  if (val == null) {
    items.value.splice(0, items.value.length)
    return
  }
  id = 1
  const list: ObjKeyValItem[] = []
  for (const i in val) {
    list.push({
      id: id++,
      name: i,
      value: val[i]
    })
  }
  items.value.splice(0, items.value.length, ...list)
}
const drop = (item: ObjKeyValItem) => {
  const index = items.value.findIndex((c) => c.id == item.id)
  if (index != -1) {
    items.value.splice(index, 1)
  }
}
const add = () => {
  items.value.push({
    id: id++,
    name: '',
    value: ''
  })
}
const format = (items: ObjKeyValItem[]) => {
  if (items == null || items.length == 0) {
    return {}
  }
  const obj = {}
  items.forEach((c) => {
    if (c.name != '' && c.value != '') {
      obj[c.name] = c.value
    }
  })
  return obj
}
watch(
  () => unref(items),
  (val: ObjKeyValItem[]) => {
    emit('update:modelValue', format(val))
  },
  {
    immediate: false,
    deep: true
  }
)
</script>
